<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
// import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElMessage } from 'element-plus'
import { userGroupEdit, userGroupIndex } from '@/api/common'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { userGroupType } from '@/api/common/types'
import { ref, reactive, h } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useRouter } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
// import { TableColumn } from '@/types/table'

import { useAppStoreWithOut } from '@/store/modules/app'
import { useCache } from '@/hooks/web/useCache'
const appStore = useAppStoreWithOut()
const { wsCache } = useCache()
//用户权限数组
const userRlues = wsCache.get(appStore.getUserInfo).rlues
const userId = wsCache.get(appStore.getUserInfo).id
const checkRlues = (rlues) => {
  //检查权限
  console.log(userRlues)
  if (userRlues.includes(rlues)) {
    return true
  } else {
    ElMessage.error('当前用户无权限操作，请联系管理员')
    return false
  }
}

const { push } = useRouter()

const { register, tableObject, methods } = useTable<userGroupType>({
  getListApi: userGroupIndex,
  // delListApi: userDEL,
  response: {
    list: 'data',
    total: 'total'
  },
  defaultParams: {
    title: ''
  },
  find: ''
})

const { getList } = methods

getList()

const { emitter } = useEmitt()

useEmitt({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      tableObject.currentPage = 1
    }
    getList()
  }
})

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'name',
    label: '分组名称'
  },
  {
    field: 'rules',
    label: '权限',
    formatter: (row: userGroupType) => {
      return h('span', '测试')
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('formDemo.operate'),
    form: {
      show: false
    },
    fixed: 'right',
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const AddAction = (rules) => {
  if (!checkRlues(rules)) return false
  push('/personnelManagement/userGroupingAdd')
}
const dialogTitle = ref('')

const delLoading = ref(false)

const delData = async (row: userGroupType | null, multiple: boolean, rules: string) => {
  if (!checkRlues(rules)) return false
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? selections.map((v) => v.id) : [tableObject.currentRow?.id as string],
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

const actionType = ref('')

const action = (row: TableData, type: string, rules: string) => {
  console.log(rules)
  if (!checkRlues(rules)) return false
  switch (type) {
    case 'Edit':
      {
        push(`/personnelManagement/userGrouping${type}?id=${row.id}`)
      }
      break
    default:
      break
  }
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as TableData
      const res = await userGroupEdit(data, data.id)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        getList()
      }
    }
  })
}
</script>

<template>
  <ContentWrap>
    <div class="mb-10px">
      <ElButton type="primary" @click="AddAction('32-1')">{{ t('exampleDemo.add') }}</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="delData(null, true, '32-3')">
        {{ t('exampleDemo.del') }}
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.limit"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #placestart_id="{ row }"> {{ selAddress(row.placestart_id) }} </template>
      <template #action="{ row }">
        <ElButton type="primary" @click="action(row, 'Edit', '32-2')">
          {{ t('exampleDemo.edit') }}
        </ElButton>
        <ElButton type="danger" @click="delData(row, false, '32-3')">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>
</template>
